//
//  GradientButton.swift
//  LeTu
//
//  Created by gy on 2023/11/28.
//

import UIKit

class GradientButton: UIView {

    private let gradientLayer = CAGradientLayer()
    private let textButton = UIButton()
    
    var isEnabled: Bool {
        get {
            return self.isUserInteractionEnabled
        }
        set {
            self.isUserInteractionEnabled = newValue
        }
    }
    
    var direction = UIViewGradientDirection.horizontally
    var gradientColors: [CGColor] = [UIColor.white.cgColor, UIColor.white.cgColor] {
        didSet {
            setNeedsLayout()
        }
    }
    var title: String {
        return textButton.titleLabel?.text ?? ""
    }

    func setTitle(_ title: String) {
        textButton.setTitle(title, for: .disabled)
    }
    
    func setTitleColor(_ color: UIColor) {
        textButton.setTitleColor(color, for: .disabled)
    }
    
    func setFont(_ font: UIFont) {
        textButton.titleLabel?.font = font
    }
    
    /// 添加手势
    func addTarget(_ target: Any?, action: Selector) {
        
        let tapGesture = UITapGestureRecognizer(target: target, action: action)
        self.addGestureRecognizer(tapGesture)
        self.isUserInteractionEnabled = true
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit() {
        layer.addSublayer(gradientLayer)
        
        textButton.isEnabled = false
        addSubview(textButton)
        
        textButton.setTitleColor(UIColor.white, for: .normal)
        textButton.backgroundColor = UIColor.clear
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 设置 textLabel 的 frame
        textButton.frame = bounds
        
        // 设置渐变层的大小和位置
        gradientLayer.frame = bounds

        // 设置渐变层的颜色
        gradientLayer.colors = gradientColors

        // 设置渐变的方向，这里是横向
        if direction == .horizontally {
            gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
            gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
        } else {
            gradientLayer.startPoint = CGPoint.init(x: 0, y: 0)
            gradientLayer.endPoint = CGPoint.init(x: 0, y: 1)
        }
    }

}
